package org.pragma;

import java.util.HashMap;
import java.util.Map;

import org.pragma.objects.PragmaObject;
import org.pragma.objects.PragmaString;

public class PragmaContext extends PragmaObject{

	Map<String,PragmaObject> objects = new HashMap<String,PragmaObject>();
	Map<String,PragmaClass> classes = new HashMap<String,PragmaClass>();
	PragmaContext parent;
	String contextTitle;

	public PragmaObject findObject(PragmaReference callee) throws Exception {
		PragmaObject result = null;
		if(callee.isFromThis()){
			PragmaObject theThis = findObject("this");
			 result = theThis.getContext().findObject(callee.getName());
		}else{
			result = findObject(callee.getName());
		}
		return result;
	}
	
	public PragmaObject findObject(String callee) throws Exception {
		PragmaObject po = objects.get(callee.intern());
		if(po==null&&parent!=null){
			po=parent.findObject(callee);
		}
		
		if(po==null){
			throw new Exception("can't found "+callee);
		}		
		return po;
	}

	public void set(String key, PragmaObject pragmaObject) {
		objects.put(key.intern(),pragmaObject);	
	}
	
	public void setParent(PragmaContext ctx) {
		this.parent = ctx;
		
	}

	public void setClass(String key, PragmaClass value) {
		this.classes.put(key.intern(), value);
	}

	public PragmaClass findClass(PragmaString classString) throws Exception {
		PragmaClass pc = this.classes.get(classString.toString().intern());
		if(pc==null&&parent!=null){
			pc = parent.findClass(classString);
		}
		
		if(pc==null){
			throw new Exception("can't found "+classString);
		}
		return pc; 
	}

	public PragmaContext getParent() {
		return parent;
	}
	public String toString(){
		return getCtxTitle();
	}
	
	public String getCtxTitle() {
		String result = "";
		if(parent!=null){
			result = parent.getCtxTitle();
		}
		return result+"/"+contextTitle;
	}

	public void setCtxTitle(String ctxTitle) {
		this.contextTitle = ctxTitle;
	}
	
	
}
